package cn.com.callback;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.MultipartResolver
import org.springframework.web.multipart.commons.CommonsMultipartResolver
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat
import java.util.Iterator;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.JSONException;

/**
 *
 * @Title: ApiBPUpload
 * @Description:深圳宝安排水系统工单图片上传接口--内部接口
 * @author: chieh
 * @date 2020-11-15 21:28:00
 *
 */

public class ApiBPUpload implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(ApiBPUpload.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("utf-8"); //设置编码
		log.debug("request:"+request);

		String filePath = "";
		String outData = "";
		long startTime = System.currentTimeMillis();
		long endTime = 0;

		JSONArray jsonArray = new JSONArray();
		// json对象
		JSONObject json = new JSONObject();

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		String date = df.format(System.currentTimeMillis());

		String realPath = "C:\\elitefile\\ftp\\fs\\applets\\"+date;
		log.debug("realPath:"+realPath);
		File dir = new File(realPath);
		log.debug("dir:"+dir);
		//文件目录不存在，就创建一个
		if (!dir.isDirectory()) {
			log.debug("//不存在");
			dir.mkdirs();
		}else{
			log.debug("//目录存在");
		}

		try {
			MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			log.debug("resolver:"+resolver);
			MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
			log.debug("multipartRequest:"+multipartRequest);

			//StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
			//获取formdata的值
			Iterator<String> iterator = multipartRequest.getFileNames();
			String filename;
			//while (iterator.hasNext()) {
			MultipartFile file = multipartRequest.getFile(iterator.next());
			log.debug("file:"+file);
			String fileName = file.getOriginalFilename();
			log.debug("fileName:"+fileName);
			//真正写到磁盘上
			String uuid = UUID.randomUUID().toString().replace("-", "");
			log.debug("uuid:"+uuid);
			String kzm = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
			log.debug("kzm"+kzm);
			
			// 检查文件拓展名是否合法 jpg，jpeg或png
			if (!kzm.equals(".jpg")&&!kzm.equals(".jpeg")&&!kzm.equals(".png")&&!kzm.equals(".heic")) {
				outData="文件类型非法！";
				return outData;
			}
			
			filename = uuid + kzm;
			log.debug("filename"+filename);
			File file1 = new File(realPath +"\\"+ filename);
			OutputStream out = new FileOutputStream(file1);
			out.write(file.getBytes());
			out.close();

			filePath="https://callcenterwx.szbaps.com/ngs/fs/get?file=applets/"+date+"/"+filename;
			log.debug("图片路径:" + filePath);
			//}

			json.put("url",filePath);

			jsonArray.add(json);
			endTime = System.currentTimeMillis();
			//outData = "{\"resultcode\":\"1\",\"resultmessage\":\"上传成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonArray.toString()+"}";
			outData=filePath;


			FTPClient ftp = new FTPClient();
			log.debug("准备连接到ftp");
			try {
				//连接
				ftp.connect("192.168.0.157", 21);

				//登录
				boolean loginS = ftp.login("ngs", "Letmein_0308");
				if (!loginS) {
					log.debug("ftp登录失败，用户名或密码错误");
					return;
				}

				// 143服务器特殊。需获取本地文件并上传给142
				String file143 = realPath+"\\"+filename;
				FileInputStream input = new FileInputStream(file143);
				String dirname="ftp\\fs\\applets\\"+date+"\\";
				ftp.makeDirectory(dirname);
				log.debug("在目标服务器上成功建立了文件:"+dirname);
				ftp.changeWorkingDirectory(dirname);//跳转目录
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//必须要设置以二进制的方式传输文件
				ftp.enterLocalPassiveMode();//被动模式
				//ftp.enterLocalActiveMode();//主动模式，默认是主动模式

				if (!ftp.storeFile(new File(file143).getName(), input)) {
					log.debug("失败，服务器返回:" + ftp.getReplyString());//获取上传失败的原因
				} else {
					log.debug("文件:" + new File(file143).getName() + " 上传成功");
				}
				input.close();
				ftp.logout();
			} catch (IOException e) {
				log.debug("ftp连接失败");
			}
			//传给142后，删除143的文件
			//deleteFile(realPath +"\\"+ filename);
			//--------------------------------end--------------------------------------------------

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			//outData = "{\"resultcode\":\"0\",\"resultmessage\":\"上传处理失败(" + e.getMessage() + ")\"}";
			outData=e.getMessage();
		}
		return outData;

	}
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}


}